<!--  -->
<template>
  <div>
         <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card>
      <!-- 步骤条 -->
      <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center class="steps">
        <el-step title="基本信息"></el-step>
        <el-step title="规格参数"></el-step>
        <el-step title="销售属性"></el-step>
        <el-step title="sku信息"></el-step>
        <el-step title="添加完成"></el-step>
      </el-steps>
      <!-- tab栏区 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" >
        <el-tabs v-model="activeIndex" :tab-position="'left'"  
          :before-leave="beforeTabLeave" @tab-click="tabClicked">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="proName">
              <el-input v-model="addForm.proName"></el-input>
            </el-form-item>
            <el-form-item label="商品描述" prop="proDescription">
              <el-input v-model="addForm.proDescription"></el-input>
            </el-form-item>
            <!-- <el-form-item label="商品重量" prop="weight">
              <el-input v-model="addForm.weight"></el-input>
            </el-form-item> -->
           
            <el-form-item label="选择分类" prop="catalogId">
              <!-- <el-input v-model="addForm.catalogId"> -->
                <el-cascader
                ref="cascader"
                @change="handleChange"
                v-model="addForm.catalogId"
                :options="categories" :props="props">
                </el-cascader>
              <!-- </el-input> -->
            </el-form-item>
             <el-form-item label="选择品牌" prop="brandId">
              <el-select v-model="addForm.brandId" placeholder="请选择">
                <el-option
                  v-for="(item,i) in brands"
                  :key="i"
                  :label="item.brandName"
                  :value="item.brandId">
                </el-option>
              </el-select>
            </el-form-item>
             <el-form-item label="价格" prop="price">
              <el-input v-model="addForm.price"></el-input>
            </el-form-item>
            <el-form-item label="重量(kg)" prop="weight">
              <el-input v-model="addForm.weight"></el-input>
            </el-form-item>
            <el-form-item label="库存" prop="stockCount">
              <el-input  v-model="addForm.stockCount"></el-input>
            </el-form-item> 
            <el-form-item label="商品图集" prop="images">
              <OssUploads v-model="images" ref="OssUploads1"></OssUploads>
            </el-form-item>
             <el-form-item label="商品介绍" prop="decript">
              <OssUploads v-model="decript" ref="OssUploads2"></OssUploads>
            </el-form-item>
            <!-- <el-button type="primary" @click="activeIndex = 1">上一步</el-button> -->
            <el-button type="success" @click="jump('1')">下一步：规格参数</el-button>
          </el-tab-pane>
          <el-tab-pane label="规格参数" name="1">
            <el-form-item  :label="item.attrName" v-for="(item,i) in addForm.baseAttrs" :key="i"  >   
              <el-input v-model="item.attrValues"></el-input>
              <!-- <el-checkbox-group v-model="item.valueSelect">
                <el-checkbox border :label="item1" v-for="(item1,i) in item.valueSelect" :key="i"></el-checkbox>
              </el-checkbox-group> -->
            </el-form-item>
            <el-button type="primary" @click="jump('0')">上一步</el-button>
            <el-button type="success" @click="jump('2')">下一步：销售属性</el-button>
          </el-tab-pane>
          <el-tab-pane label="销售属性" name="2">
            <el-form-item
             :label="item.attrName" v-for="(item,i) in attrs" :key="i"
            >
              <el-input
                v-model="tempSaleAttrs[i].attrId"
                type="hidden"
                v-show="false"
              ></el-input>
              <el-checkbox-group v-model="tempSaleAttrs[i].attrValues">
                <el-checkbox
                  :label="val"
                  v-for="val in item.valueSelect.split('，')"
                  :key="val"
                ></el-checkbox>
                <div style="margin-left:20px;display:inline">
                  <el-button
                    v-show="!inputVisible[i].view"
                    class="button-new-tag"
                    size="small"
                    @click="showInput(i)"
                  >+自定义</el-button>
                  <el-input
                    v-show="inputVisible[i].view"
                    v-model="inputValue[i].val"
                    :ref="'saveTagInput'+ i"
                    size="small"
                    style="width:150px"
                    @keyup.enter.native="handleInputConfirm(i)"
                    @blur="handleInputConfirm(i)"
                  ></el-input>
                </div> 
              </el-checkbox-group>
            </el-form-item>
            <el-button type="primary" @click="jump('1')">上一步</el-button>
            <el-button type="success" @click="jump('3')">下一步 sku信息</el-button>
            <!-- <el-button type="primary" @click="addGoodsInfo">保存sku信息</el-button> -->
          </el-tab-pane>
          <el-tab-pane label="sku信息" name="3">
            <el-table :data="addForm.skus" style="width: 100%">
            <el-table-column label="属性组合">
              <el-table-column
                :label="item.attrName"
                v-for="(item,index) in tableAttrColumn"
                :key="item.attrId"
              >
                <template slot-scope="scope">
                  <span style="margin-left: 10px">{{ scope.row.attr[index].attrValue }}</span>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column label="商品名称" prop="skuName">
              <template slot-scope="scope">
                <el-input v-model="scope.row.skuName"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="标题" prop="skuTitle">
              <template slot-scope="scope">
                <el-input v-model="scope.row.skuTitle"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="价格" prop="price">
              <template slot-scope="scope">
                <el-input v-model="scope.row.price"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="重量" prop="weight">
              <template slot-scope="scope">
                <el-input v-model="scope.row.weight"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="库存" prop="stockCount">
              <template slot-scope="scope">
                <el-input v-model="scope.row.stockCount"></el-input>
              </template>
            </el-table-column>
            </el-table>
            <el-button type="primary" @click="jump('2')">上一步</el-button>
            <el-button type="success" @click="addGoods">添加商品</el-button>
           <!-- <el-button type="primary" @click="addGoods">添加完成</el-button> -->
          </el-tab-pane>
          <el-tab-pane label="添加完成" name="4">
            <h1>添加成功</h1>
          <el-button type="primary" @click="addAgian">继续添加</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import OssUploads from '../../components/OssUploads'
export default {
  data () {
    return {
      activeIndex:"0",
      // 添加商品的表单数据
      addForm:{
        proName:"",
        proSku:1,
        proDescription:"",
        brandId:'',
        catalogId:'',
        publishStatus:1,
        images:[],
        decript:[],
        // 规格参数数据
        baseAttrs:[],
        skus:[],
      },
      decript:[],
      images:[],
      // 获取的sku信息
      attrs:[],
      tempSaleAttrs:[],
      skuImages:[],
      skuData:{
       attr:[],
       skuName: "",
       price: '',
       skuTitle: "",
       images:[],
       descar: "",
       weight: "",
       stockCount: ''
      },
      
      // 品牌选择器数据
      brands:[],
      // 级联选择器
      props:{
          value:"catId",
          label:'name',
          children:"children"
        },
      // 级联数据
     // 级联菜单数据
     categories:[],
      // 表单的验证规则
      addFormRules:{
        proName:[{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        price:[{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        brandId:[{ required: true, message: '请选择品牌', trigger: 'blur' }],
        catalogId:[{ required: true, message: '请选择商品分类', trigger: 'blur' }],
        proDescription:[{ required: true, message: '请输入商品描述', trigger: 'blur' }],
        weight:[{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        price:[{ required: true, message: '请输入商品的最低价格', trigger: 'blur' }],
        stockCount:[{ required: true, message: '请输入商品库存', trigger: 'blur' }],
      },
      tableAttrColumn:[],
      inputVisible: [],
      inputValue: []
    };
  },
  components:{
    OssUploads
  },
  created(){
    this.getCategoriesList()
    this.images = [],
    this.decript = []
  },
  // 监听属性值的改变，进而改变sku商品名
  watch:{
    attrs: {
      handler(newName, oldName) {
        const goodsName=[]
        newName.forEach(item =>{
          goodsName.push(item.attrValue)  
        })
        // console.log(newName)
        this.skuData.skuName =  this.addForm.proName + ' ' + goodsName.join(" ")
      // console.log(this.skuData.skuName)
    },
    deep: true,
    immediate: true
    },
    images: {
      handler(newName, oldName) {
        const goodsImages=[]
        newName.forEach(item =>{
          goodsImages.push(item.url)  
        })
        this.addForm.images =  goodsImages
      // console.log(this.addForm.images)
    },
    deep: true,
    immediate: true
    },
    decript: {
      handler(newName, oldName) {
        const goodsDecript=[]
        newName.forEach(item =>{
          goodsDecript.push(item.url)  
        })
        this.addForm.decript =  goodsDecript
      // console.log(this.addForm.decript)
    },
    deep: true,
    immediate: true
    }
  },
  methods:{
    // 继续添加
    addAgian() {
      this.activeIndex = '0';
      this.resetSpuData();
    },
    resetSpuData() {
      this.images = []
      this.decript=[]
     this.$refs.OssUploads1.$refs.upload.clearFiles()
     this.$refs.OssUploads2.$refs.upload.clearFiles()
      this.addForm = {

        spuName: "",
        spuDescription: "",
        catalogId: 0,
        brandId: "",
        decript: [], 
        images: [], 
        weight:'',
        price:'',
        stockCount:"",
        // bounds: {
        //   buyBounds: 0,
        //   growBounds: 0
        // },
        baseAttrs: [], 
        skus: []
      };
    },
    // 获取级联分类数据
      async  getCategoriesList(){
      const {data:res} = await this.$http.get("/dqxmall/prosyscategory/list/tree")
      this.categories = res.data
    },
    // 当选节点点击时触发
    handleChange(){
      this.brands = []
      var nodeInfo = this.$refs.cascader.getCheckedNodes()
      // console.log(nodeInfo)
      this.addForm.catalogId = nodeInfo[0].data.catId;
      this.getBrands()
    },
    // 获取所有品牌
    async  getBrands(){
      const {data:res} = await this.$http.get(`/dqxmall/prosysbrandcategoryrelation/brands/list?catId=${this.addForm.catalogId}`)
      // console.log(res)
      this.brands = res.data
    },
   
    // 离开标签页
    beforeTabLeave(activeName,oldActiveName){
      console.log("即将离开的标签页名",oldActiveName)
      // console.log("即将进入的标签页名",activeName)
      if(oldActiveName === '0' && this.addForm.catalogId === ''){
        this.$message.error("请先选择商品分类")
        return false
      }
    },
      jump(value){
        this.activeIndex = value
        this.tabClicked()
      },
    // 点击标签。发送参数请求
    async  tabClicked(){
      // console.log(this.activeIndex)
      // 证明访问的是商品参数面板
      if(this.activeIndex === '1'){
        // 根据选中的分类id发送请求 获取动态参数
      const {data:res} = await this.$http.get(`/dqxmall/prosysattrgroup/${this.addForm.catalogId}/withattr`)
      // console.log("base",res)
      
        if(res.code !== 0 ){
          return 0
        }
        this.addForm.baseAttrs = []
        res.data.forEach(item => {
          if(item.attrs.length){
            item.attrs.forEach(item1 => {
            // item1.valueSelect = item1.valueSelect ? item1.valueSelect.split('，') : []
            const data={}
            data.attrId = item1.attrId,
            data.attrName = item1.attrName,
            data.attrValues = item1.valueSelect
            this.addForm.baseAttrs.push(data)
          })  
          }
        });
        //  console.log(this.addForm.baseAttrs )
      }
      else if(this.activeIndex === '2'){
        // 根据选中的分类id发送请求 获取销售属性
      const {data:res} = await this.$http.get(`/dqxmall/prosysattr/sale/list/${this.addForm.catalogId}`)
      // console.log("saleattr",res)
        if(res.code !== 0 ){
          return 0
        }
        this.attrs=[]
        this.attrs =  res.page.list,
          res.page.list.forEach(item1 => {
            this.tempSaleAttrs.push({
              attrId: item1.attrId,
              attrValues: [],
              attrName: item1.attrName
            })
             this.inputVisible.push({ view: false });
           this.inputValue.push({ val: "" });
          }) ;
          // console.log("at",this.attrs)
      }
      else if(this.activeIndex === '3'){
        //根据笛卡尔积运算进行生成sku
      let selectValues = [];
      this.tableAttrColumn = [];
      this.tempSaleAttrs.forEach(item => {
        if (item.attrValues.length > 0) {
          selectValues.push(item.attrValues);
          this.tableAttrColumn.push(item);
        }
      });
      
      let descartes = this.descartes(selectValues);
      // console.log("生成的组合", JSON.stringify(descartes));
     
      let skus = [];
      descartes.forEach((descar, descaridx) => {
        let attrArray = []; //sku属性组
        descar.forEach((de, index) => {
          //构造saleAttr信息
          let saleAttrItem = {
            attrId: this.tableAttrColumn[index].attrId,
            attrName: this.tableAttrColumn[index].attrName,
            attrValue: de
          };
          attrArray.push(saleAttrItem);
        });
        // console.log("this.tableAttrColumn",this.tableAttrColumn)
        // 先初始化几个images，后面的上传还要加
        let imgs = [];
        this.addForm.images.forEach((img, idx) => {
          imgs.push({ imgUrl:img, defaultImg: 0 });
          imgs[0].defaultImg = 1;
        });
        skus.push({
          attr: attrArray,
          skuName: this.addForm.proName + " " + descar.join(" "),
          price: this.addForm.price,
          skuTitle: this.addForm.proDescription,
          // skuSubtitle: "",
          stockCount: this.addForm.stockCount,
          weight:this.addForm.weight,
          images: imgs,
        });
      });
      this.addForm.skus = skus;
      console.log('this.addForm.skus',this.addForm.skus)
      }
    },
    // 显示输入框
    showInput(idx) {
      this.inputVisible[idx].view = true;
    },
    handleInputConfirm(idx) {
      let inputValue = this.inputValue[idx].val;
      if (inputValue) {
        // this.dynamicTags.push(inputValue);
        if (this.attrs[idx].valueSelect == "") {
          this.attrs[idx].valueSelect = inputValue;
        } else {
          this.attrs[idx].valueSelect += "，" + inputValue;
        }
      }
      this.inputVisible[idx].view = false;
      this.inputValue[idx].val = "";
      // console.log(this.attrs)
    },
    // 添加商品
    async  addGoods(){
      console.log("最后添加的商品",this.addForm)
      // 发送请求
      const {data:res} = await this.$http.post('/dqxmall/prosysproinfo/save',this.addForm)
      // console.log(res)
      if(res.code !== 0){
        this.$message.error("保存失败")
        return 0
      }
      this.$message.success("保存成功")
      this.jump('4')
    },
    //笛卡尔积运算
    descartes(list) {
      //parent上一级索引;count指针计数
      var point = {};
      var result = [];
      var pIndex = null;
      var tempCount = 0;
      var temp = [];

      //根据参数列生成指针对象
      for (var index in list) {
        if (typeof list[index] == "object") {
          point[index] = { parent: pIndex, count: 0 };
          pIndex = index;
        }
      }

      //单维度数据结构直接返回
      if (pIndex == null) {
        return list;
      }

      //动态生成笛卡尔积
      while (true) {
        for (var index in list) {
          tempCount = point[index]["count"];
          temp.push(list[index][tempCount]);
        }

        //压入结果数组
        result.push(temp);
        temp = [];

        //检查指针最大值问题
        while (true) {
          if (point[index]["count"] + 1 >= list[index].length) {
            point[index]["count"] = 0;
            pIndex = point[index]["parent"];
            if (pIndex == null) {
              return result;
            }
            //赋值parent进行再次检查
            index = pIndex;
          } else {
            point[index]["count"]++;
            break;
          }
        }
      }
    }
  }
}

</script>
<style lang='less' scoped>
.el-checkbox{
  margin: 0 5px 0 0 !important;
}
.steps{
  margin: 20px;
}
</style>